//
//  LGECGDetailViewController2.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2024/8/20.
//  心电图2

#import "LGECGDetailViewController2.h"
#import "LGECGDetailHeaderView.h"
#import "LGECGDetailRiskCell.h"
#import "LGECGDetailScoreCell.h"
#import "LGECGDetailMedicineCell.h"
@interface LGECGDetailViewController2 ()<UITableViewDataSource,UITableViewDelegate,LGBottomButtonDelegate>
/**   */
@property (nonatomic , strong)LGECGDetailHeaderView *headView;
/**   */
@property (nonatomic , strong)LGBottomButtonView *bottomView;
/**   */
@property (nonatomic , strong)UITableView *tableView;
/**   */
@property (nonatomic , strong)UILabel *statusLabel;
/**   */
@property (nonatomic , strong)UILabel *cvdLabel;
/**   */
@property (nonatomic , strong)NSDictionary *dataDic;
/**   */
@property (nonatomic , strong)NSArray *riskArray;
/**   */
@property (nonatomic , strong)NSArray *scoreArray;
/**   */
@property (nonatomic , strong)NSDictionary *cvdData;
/**   */
@property (nonatomic , strong)NSDictionary *ecgDic;
/**   */
@property (nonatomic , strong)NSDictionary *ecgData;
/**   */
@property (nonatomic , strong)NSMutableArray *ecgArray;
/**   */
@property (nonatomic , copy)NSString *reportUrl;

@end

@implementation LGECGDetailViewController2

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"常规心电图检测报告";
    self.cvdData = @{};
    self.ecgData = @{};
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomView];
    [self emptyViewWithSuperView:self.view frame:CGRectMake(0, 0, Screen_W, Screen_H-topBarHeight-viewPix(70)-bottomSafeBarHeight/4.0)];
    self.emptyView.backgroundColor = [UIColor colorWithString:@"#F3F7F8"];
    
    self.scoreArray = @[
        @{@"title":@"心律变异性",@"scoreKey":@"hrvScore",@"indexKey":@"hrvIndex",@"items":@[@{@"title":@"严重偏低",@"color":@"#C14D4D",@"minValue":@"0",@"maxValue":@"12"},@{@"title":@"偏低",@"color":@"#FEBB36",@"minValue":@"12",@"maxValue":@"26"},@{@"title":@"正常",@"color":@"#5597F5",@"minValue":@"26",@"maxValue":@"82"},@{@"title":@"偏高",@"color":@"#FE6603",@"minValue":@"82",@"maxValue":@"100"}],@"segments":@[@"12",@"26",@"82"],@"indexDic":@{@"-1":@"-1",@"3":@"0",@"0":@"1",@"1":@"2",@"2":@"3"}},
        @{@"title":@"饮酒风险指数",@"scoreKey":@"alcoholRiskScore",@"indexKey":@"alcoholRiskIndex",@"items":@[@{@"title":@"低",@"color":@"#5597F5",@"minValue":@"0",@"maxValue":@"20"},@{@"title":@"中低",@"color":@"#FEB803",@"minValue":@"20",@"maxValue":@"40"},@{@"title":@"偏高",@"color":@"#FE9636",@"minValue":@"40",@"maxValue":@"55"},@{@"title":@"中高",@"color":@"#FE6603",@"minValue":@"55",@"maxValue":@"70"},@{@"title":@"高",@"color":@"#C14D4D",@"minValue":@"70",@"maxValue":@"100"}],@"segments":@[@"20",@"40",@"55",@"70"],@"indexDic":@{@"-1":@"-1",@"0":@"0",@"1":@"1",@"2":@"2",@"3":@"3",@"4":@"4"}},
        @{@"title":@"疲劳度",@"scoreKey":@"stressScore",@"indexKey":@"stressIndex",@"items":@[@{@"title":@"正常",@"color":@"#5597F5",@"minValue":@"0",@"maxValue":@"25"},@{@"title":@"轻度",@"color":@"#FEBB36",@"minValue":@"25",@"maxValue":@"50"},@{@"title":@"中度",@"color":@"#FE6603",@"minValue":@"50",@"maxValue":@"75"},@{@"title":@"重度",@"color":@"#C14D4D",@"minValue":@"75",@"maxValue":@"100"}],@"segments":@[@"25",@"50",@"75"],@"indexDic":@{@"-1":@"-1",@"0":@"0",@"1":@"1",@"2":@"2",@"3":@"3"}},
        @{@"title":@"心脏压力指数",@"scoreKey":@"heartPressureScore",@"indexKey":@"heartPressureIndex",@"items":@[@{@"title":@"低风险",@"color":@"#5597F5",@"minValue":@"0",@"maxValue":@"30"},@{@"title":@"中低风险",@"color":@"#FEBB36",@"minValue":@"30",@"maxValue":@"60"},@{@"title":@"中高风险",@"color":@"#FE6603",@"minValue":@"60",@"maxValue":@"80"},@{@"title":@"高风险",@"color":@"#C14D4D",@"minValue":@"80",@"maxValue":@"100"}],@"segments":@[@"30",@"60",@"80"],@"indexDic":@{@"-1":@"-1",@"0":@"0",@"1":@"1",@"2":@"2",@"3":@"3"}}
    ];
    
    self.ecgDic = @{@"aveHr":@{@"title":@"心率",@"unit":@"bmp",@"min":@"60",@"max":@"100"},
                    @"qt":@{@"title":@"QT间期",@"unit":@"ms",@"min":@"320",@"max":@"480"},
                    @"qtc":@{@"title":@"QTc",@"unit":@"ms",@"min":@"320",@"max":@"480"},
                    @"qrsTime":@{@"title":@"QRS时限",@"unit":@"ms",@"min":@"60",@"max":@"110"},
                    @"pwaveTime":@{@"title":@"P波时限",@"unit":@"ms",@"min":@"60",@"max":@"110"},
                    @"prIntervalTime":@{@"title":@"PR间期",@"unit":@"ms",@"min":@"120",@"max":@"210"}
    };
    
    [self requestData];
}

-(void)requestData{
    [RequestUtil withPOST:@"/doctor/patient.Physicalsign/ecgDetail" parameters:@{@"patient_id":self.patientid,@"ecg_id":self.ecgId} withSign:YES success:^(NSInteger code, NSString *message, id returnData) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
        if(code == 200){
            if ([returnData[@"airesult"] isKindOfClass:[NSDictionary class]] && [returnData[@"airesult"] allKeys].count>1) {
                self.dataDic = returnData[@"airesult"];
                self.headView.dataDic = returnData[@"airesult"];
                self.statusLabel.text = [NSString stringWithFormat:@"【%@】",returnData[@"airesult"][@"result"]];
                self.riskArray = returnData[@"airesult"][@"classProbabilities"];
                if ([self.source isEqualToString:@"KPQ6"]) {
//                    self.cvdData = [self.dataDic.allKeys containsObject:@"cvd"]?returnData[@"airesult"][@"cvd"]:@{};
                    self.cvdData = @{};//心肌梗死风险去掉了
                    self.ecgData = [self.dataDic.allKeys containsObject:@"ecgFeatures"]?returnData[@"airesult"][@"ecgFeatures"]:@{};
                }else{
                    self.cvdData = @{};
                    self.ecgData = @{};
                }
                [self.tableView reloadData];
            }
        }else{
            [self.emptyView showViewWithImage:@"emptyView2" content:message offset:0];
        }
    } error:^(NSError *error) {
        self.isfirst = NO;
        [self.emptyView stopBufferAction];
    }];
}

-(void)setCvdData:(NSDictionary *)cvdData{
    _cvdData = cvdData;
    if ([cvdData isKindOfClass:[NSDictionary class]] && cvdData.allKeys.count>0) {
        NSString *status = LGNSString(cvdData[@"miProbabilitystatus"]);
        NSDictionary *titleDic = @{@"0":@"低风险",@"1":@"中风险",@"2":@"中高风险"};
        NSDictionary *colorDic = @{@"0":@"#4C87FD",@"1":@"#FE9636",@"2":@"#FE6603"};
        NSString *title = [titleDic.allKeys containsObject:status]?titleDic[status]:@"";
        NSString *color = [colorDic.allKeys containsObject:status]?colorDic[status]:@"";
        self.cvdLabel.text = [NSString stringWithFormat:@"【%@】",title];
        self.cvdLabel.textColor = [UIColor colorWithString:color];
        
    }else{
        self.cvdLabel.text = @"";
    }
}

-(void)setEcgData:(NSDictionary *)ecgData{
    _ecgData = ecgData;
    NSArray *tempArray = @[@"aveHr",@"pwaveTime",@"prIntervalTime",@"qrsTime",@"qt",@"qtc"];
    [self.ecgArray removeAllObjects];
    if ([ecgData isKindOfClass:[NSDictionary class]] && ecgData.allKeys.count>0) {
        NSArray *keyArray = ecgData.allKeys;
        for (NSString *string in tempArray) {
            if ([keyArray containsObject:string]) {
                [self.ecgArray addObject:string];
            }
        }
    }
}
//查看完整心电图
-(void)bottomButtonTouched{
    LGGetWebViewController *controller = [[LGGetWebViewController alloc]init];
    controller.urlStr = LGNSString(self.dataDic[@"report_url"]);
    [self.navigationController pushViewController:controller animated:YES];
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(section == 0){
        //心律失常风险
        return self.riskArray.count;
        
    }else if(section == 2){
        //HRV指标
        return self.scoreArray.count;
        
    }else if(section == 3){
        //ECG医学指标
        return self.ecgArray.count;
        
    }else{
        //心肌梗死风险
        return 0;
    }
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        LGECGDetailRiskCell *riskCell = [tableView dequeueReusableCellWithIdentifier:@"riskCell" forIndexPath:indexPath];
        riskCell.selectionStyle = UITableViewCellSelectionStyleNone;
        riskCell.dataDic = self.riskArray[indexPath.row];
        return riskCell;
        
    }else if(indexPath.section == 2){
        LGECGDetailScoreCell *scoreCell = [tableView dequeueReusableCellWithIdentifier:@"scoreCell" forIndexPath:indexPath];
        scoreCell.selectionStyle = UITableViewCellSelectionStyleNone;
        scoreCell.lineView.hidden = (indexPath.row<self.scoreArray.count-1)?NO:YES;
        NSDictionary *tempDic = self.scoreArray[indexPath.row];
        scoreCell.dataDic = tempDic;
        NSString *scoreKey = LGNSString(tempDic[@"scoreKey"]);
        NSString *indexKey = LGNSString(tempDic[@"indexKey"]);
        NSDictionary *indexDic = tempDic[@"indexDic"];
        if (_dataDic && [self.dataDic.allKeys containsObject:scoreKey] && [self.dataDic[@"timelength"] integerValue]>30) {
            scoreCell.showData = YES;
            scoreCell.resultDic = @{@"score":LGNSString(self.dataDic[scoreKey]),@"index":indexDic[LGNSString(self.dataDic[indexKey])]};
        }else{
            scoreCell.resultDic = @{@"score":@"0",@"index":@"-1"};
            scoreCell.showData = NO;
        }
        return scoreCell;
    }else if (indexPath.section == 3){
        LGECGDetailMedicineCell *medicineCell = [tableView dequeueReusableCellWithIdentifier:@"medicineCell" forIndexPath:indexPath];
        medicineCell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSString *key = self.ecgArray[indexPath.row];
        medicineCell.dataDic = self.ecgDic[key];
        medicineCell.value = [self.ecgData[key] integerValue];
        return medicineCell;
    }
    return nil;
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    CGFloat height = 0.01;
    if(section == 0){
        //心律失常风险
        height = viewPix(100);
        
    }else if(section == 1 && self.cvdData.allKeys.count>0){
        //心肌梗死风险
        height = viewPix(145);
        
    }else if(section == 2){
        //HRV指标
        height = viewPix(50);
        
    }else if(section == 3 && self.ecgArray.count>0){
        //ECG医学指标
        height = viewPix(50);
        
    }
    return height;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    CGFloat height = 0.01;
    if(section == 0){
        //心律失常风险
        height = viewPix(100);
        
    }else if(section == 1 && self.cvdData.allKeys.count>0){
        //心肌梗死风险
        height = viewPix(145);
        
    }else if(section == 2){
        //HRV指标
        height = viewPix(50);
        
    }else if(section == 3 && self.ecgArray.count>0){
        //ECG医学指标
        height = viewPix(50);
    }
    LGCornerHeaderView *headView = [[LGCornerHeaderView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, height)];
    headView.topMargin = viewPix(8);
    NSArray *titleArray = @[@"心律失常风险",@"心肌梗死风险",@"HRV指标",@"ECG医学指标"];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(viewPix(28), viewPix(26), 4, viewPix(14))];
    lineView.backgroundColor = [UIColor colorWithString:@"#77D4C6"];
    lineView.cornerRidus = 2;
    [headView addSubview:lineView];
    
    UILabel *titleLabel = [UILabel lableWithText:titleArray[section] colorString:@"#282828" textFont:LGFontWeight(18, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
    titleLabel.frame = CGRectMake(viewPix(39), viewPix(20), viewPix(200), viewPix(26));
    [headView addSubview:titleLabel];
    
    if(section == 0){
        [headView addSubview:self.statusLabel];
        
    }else if (section == 1){
        [headView addSubview:self.cvdLabel];
        UILabel *tipLabel = [UILabel lableWithText:@"本产品为标准肢体六导联，可反映心脏下壁及高壁心肌梗死表现" colorString:@"#909399" textFont:LGFont(14) textAlignment:NSTextAlignmentLeft lines:2];
        [headView addSubview:tipLabel];
        [tipLabel lineSpacing:5];
        [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.cvdLabel.mas_bottom).offset(viewPix(12));
            make.left.equalTo(headView).offset(viewPix(28));
            make.right.equalTo(headView).offset(-viewPix(28));
        }];
    }
    return headView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    CGFloat height = viewPix(15);
    if((section == 1 && self.cvdData.allKeys.count == 0)||(section == 3 && self.ecgArray.count == 0)){
        //心肌梗死风险
        height = 0.01;
    }
    return height;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    CGFloat height = viewPix(15);
    if((section == 1 && self.cvdData.allKeys.count == 0)||(section == 3 && self.ecgArray.count == 0)){
        //心肌梗死风险
        height = 0.01;
    }
    LGCornerFooterView *footerView = [[LGCornerFooterView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, height)];
    footerView.backgroundColor = [UIColor clearColor];
    footerView.bottomMargin = viewPix(8);
    return footerView;
}


-(UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Screen_W, Screen_H-topBarHeight-viewPix(70)-bottomSafeBarHeight/4.0) style:UITableViewStyleGrouped];
        [_tableView registerClass:[LGECGDetailRiskCell class] forCellReuseIdentifier:@"riskCell"];
        [_tableView registerClass:[LGECGDetailScoreCell class] forCellReuseIdentifier:@"scoreCell"];
        [_tableView registerClass:[LGECGDetailMedicineCell class] forCellReuseIdentifier:@"medicineCell"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.rowHeight = UITableViewAutomaticDimension;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.tableHeaderView = self.headView;
        _tableView.tableFooterView = [self tableFooterView];
    }
    return _tableView;
}


-(UILabel *)statusLabel{
    if(!_statusLabel){
        _statusLabel = [UILabel lableWithText:@"" colorString:@"#4C87FD" textFont:LGFontWeight(24, UIFontWeightSemibold) textAlignment:NSTextAlignmentCenter lines:1];
        _statusLabel.frame = CGRectMake(viewPix(20), viewPix(58), Screen_W-viewPix(40), viewPix(36));
    }
    return _statusLabel;
}

-(UILabel *)cvdLabel{
    if(!_cvdLabel){
        _cvdLabel = [UILabel lableWithText:@"" colorString:@"#4C87FD" textFont:LGFontWeight(24, UIFontWeightSemibold) textAlignment:NSTextAlignmentCenter lines:1];
        _cvdLabel.frame = CGRectMake(viewPix(20), viewPix(58), Screen_W-viewPix(40), viewPix(36));
    }
    return _cvdLabel;
}

-(LGECGDetailHeaderView *)headView{
    if(!_headView){
        _headView = [[LGECGDetailHeaderView alloc]initWithFrame:CGRectMake(0, 0, Screen_W, viewPix(337))];
    }
    return _headView;
}

-(UIView *)tableFooterView{
    UIView *baseView = [[UIView alloc]init];
    NSString *content = @"特别说明\n1、心律失常结果是AI人工智能算法自动识别，以上结论不能代替医生诊断，仅供参考。如需详细分析，请咨询医生。\n2、心脏病发都具有“一过性”和“即时性”, 检测结果会受测量状态、姿势等因素影响，请结合自身症状进一步判断。若出现心悸心慌、头晕乏力等症状，建议再次测量及时就医。";
    CGFloat contentH = [content textHeightWithFont:LGFont(16) maxWidth:Screen_W-viewPix(35) lineSpacing:5];
    UILabel *contentLabel = [UILabel lableWithText:content colorString:@"#606266" textFont:LGFont(16) textAlignment:NSTextAlignmentLeft lines:0];
    contentLabel.frame = CGRectMake(viewPix(18), viewPix(10), Screen_W-viewPix(34), contentH);
    [contentLabel lineSpacing:5];
    [baseView addSubview:contentLabel];
    baseView.frame = CGRectMake(0, 0, Screen_W, contentH+viewPix(60));
    return baseView;
}

-(LGBottomButtonView *)bottomView{
    if(!_bottomView){
        _bottomView = [[LGBottomButtonView alloc]initWithTitle:@"查看完整心电图" color:@"#4C87FD" type:LGBottomButtonTypeBack frame:CGRectMake(0, kMaxY(self.tableView.frame), Screen_W, viewPix(70)+bottomSafeBarHeight/4.0)];
        _bottomView.delegate = self;
    }
    return _bottomView;
}

-(NSMutableArray *)ecgArray{
    if(!_ecgArray){
        _ecgArray = [NSMutableArray array];
    }
    return _ecgArray;
}

@end
